package cn.innosmart.aq.wifiset;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.tutk.p2p.ConnectionManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import cn.innosmart.aq.R;
import cn.innosmart.aq.manager.NetworkManager;
import cn.innosmart.aq.util.SharedUtil;
import cn.innosmart.aq.view.activity.base.BaseActivity;

/**
 * Created by David on 2016/3/4.
 */
public class WifiListActivity extends BaseActivity implements NetworkManager.WlanScanCallBack, NetworkManager.WlanConfigCallBack, NetworkManager.WlanDisconnectCallBack {


    private final int REFRESHCOMPELETE = 2;
    private final int CONNECTWIFI = 3;
    private Menu menus;
    private Toolbar toolbar;
    //菜单的点击监听事件
    private Toolbar.OnMenuItemClickListener onMenuItemClick = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            switch (menuItem.getItemId()) {
                case R.id.action_refresh:
                    getData();
                    break;

            }
            return true;
        }
    };
    private ListView wifiListView;
    private WifiListAdapter wifiListAdapter;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case EXIT:
                    //退出
                    exit();
                    break;
                case REFRESHCOMPELETE:
                    //获取数据成功，刷新UI
                    ArrayList<WifiBean> wifiBeans = (ArrayList<WifiBean>) msg.obj;
                    wifiListAdapter.refreshData(wifiBeans);
                    hideloadingDialog();
                    break;
                case CONNECTWIFI:
//
                    break;
            }
        }
    };

    private View.OnClickListener onWifiClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            WifiBean wifiBean = (WifiBean) v.getTag();
            showDialog(wifiBean);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wifi_list);
        //设置标题栏
        setBar();
        //获取Wifi列表数据
        getData();
        //初始化控件
        assignViews();
    }

    private void assignViews() {
        wifiListView = (ListView) findViewById(R.id.lv_wifi_list);
        wifiListAdapter = new WifiListAdapter(this);
        wifiListAdapter.setOnClickListener(onWifiClickListener);
        wifiListView.setAdapter(wifiListAdapter);
        TextView emptyView = (TextView) findViewById(R.id.tv_empty);
        emptyView.setText(getString(R.string.no_wifi));
        wifiListView.setEmptyView(emptyView);
    }

    /**
     * 获取Box的Wifi列表数据
     */
    private void getData() {
        loadingDialog();
        NetworkManager.getInstance().WLANScan(ConnectionManager.getInstance().getCurrentConnectionEntity(), this);
    }

    /**
     * 创建菜单
     *
     * @param menu
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_wifi_set, menu);
        menus = menu;
        return super.onCreateOptionsMenu(menu);
    }

    /**
     * 设置Toolbar菜单栏
     */
    private void setBar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        ((ImageView) findViewById(R.id.iv_headicon)).setImageResource(R.drawable.toolbar_back);
        toolbar.setTitle("");
        ((TextView) findViewById(R.id.tv_toolbar)).setText(R.string.wifi_list_title);
        setSupportActionBar(toolbar);
        findViewById(R.id.iv_headicon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                mDrawer.openDrawer(GravityCompat.START);
                mHandler.sendEmptyMessage(EXIT);
            }
        });
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setOnMenuItemClickListener(onMenuItemClick);
    }


    @Override
    protected void onResume() {
        super.onResume();
        toolbar.setNavigationIcon(null);
    }

    /**
     * {"code":0,"message":"Success","result":{"AP":["InnoSmart0","StarxNet001","YBX","isiot1","MPC","","ChinaNet-rzSJ","MPC Wuxi","HALL",
     * "taoshi206","CMCC-WEB","and-free","and-free","CMCC","CMCC","CMCC-WEB","CMCC","CMCC-WEB"]},
     * "type":"resp","callid":1457074095,"method":"NetworkManager.WLANScan"}
     *
     * @param ret
     * @param apJsonString
     */
    @Override
    public void onWlanScanCallBackCallBack(int ret, String apJsonString) {
        ArrayList<WifiBean> wifiBeans = new ArrayList<>();
        if (ret == 0) {
            try {
                JSONObject jsonAp = new JSONObject(apJsonString);
                String alive = "";
                try {
                    alive = jsonAp.getString("alive");
                } catch (Exception e) {
                }
                JSONArray aps = jsonAp.getJSONArray("AP");
                System.out.println("aps=" + aps);
                WifiBean wifiBean = null;
                for (int i = 0; i < aps.length(); i++) {
                    wifiBean = new WifiBean();
                    String result = (String) aps.get(i);
                    String[] results = result.split("\\|\\|\\|");
                    wifiBean.ssid = results[0];
                    try {
                        wifiBean.enctype = results[1];
                        wifiBean.signal = Integer.parseInt(results[2]);
                    } catch (Exception e) {
                    }
                    if (!alive.equals("eth0") && alive.equals(wifiBean.ssid)) {
                        wifiBean.status = 1;
                    }
                    if (SharedUtil.getInstance().readWifiInfo(wifiBean.ssid) != null) {
                        if (!TextUtils.isEmpty(SharedUtil.getInstance().readWifiInfo(wifiBean.ssid).toString())) {
//                            if (wifiBeans.get(0).status == 1) {
//                                wifiBeans.add(1, wifiBean);
//                            } else {
                            wifiBeans.add(0, wifiBean);
//                            }
                        } else {
                            wifiBeans.add(wifiBean);
                        }
                    } else {
                        wifiBeans.add(wifiBean);
                    }
                    System.out.println("wifiBeans.Size=" + wifiBeans.size());
//                    wifiBeans.add(wifiBean);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        Message message = mHandler.obtainMessage();
        message.what = REFRESHCOMPELETE;
        message.obj = wifiBeans;
        mHandler.sendMessage(message);
    }

    /**
     * 显示Wifi设置的对话框
     *
     * @param wifiBean
     */
    public void showDialog(final WifiBean wifiBean) {
        final WifiSetDialog wifiSetDialog = new WifiSetDialog(this);
        wifiSetDialog.setTitle(wifiBean.ssid);
        try {
            JSONObject jsonWifi = SharedUtil.getInstance().readWifiInfo(wifiBean.ssid);
            String password = jsonWifi.getString("password");
            if (!TextUtils.isEmpty(password)) {
                wifiSetDialog.setPasword(password);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //根据wifi类型显示安全类型内容
        TextView tvWifiSecurity = (TextView) wifiSetDialog.findViewById(R.id.txtWiFiSecurity);
        if (!TextUtils.isEmpty(wifiBean.enctype)) {
            if (wifiBean.enctype.equals("NONE")) {
                wifiSetDialog.findViewById(R.id.ll_need_password).setVisibility(View.GONE);
                tvWifiSecurity.setText(getString(R.string.wifi_open));
            } else {
                wifiSetDialog.findViewById(R.id.ll_need_password).setVisibility(View.VISIBLE);
                tvWifiSecurity.setText(wifiBean.enctype);
            }
        } else {
            wifiSetDialog.findViewById(R.id.ll_need_password).setVisibility(View.VISIBLE);
            tvWifiSecurity.setText(getString(R.string.wifi_open));
        }
        //显示信号强度， >30强  <39 弱
        TextView tvWifiSignal = (TextView) wifiSetDialog.findViewById(R.id.txtWiFiSignal);
        tvWifiSignal.setText(wifiBean.signal > 30 ? getString(R.string.wifi_signal_strong) : getString(R.string.wifi_signal_weak));
        //根据连接状态，设置不同的显示界面，如果已连接，则显示 断开连接，如果未连接 则显示连接
        if (wifiBean.status == 1) {
            wifiSetDialog.setPositiveButton(getString(R.string.disconnect), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    loadingDialog();
                    NetworkManager.getInstance().WLANDisconnect(ConnectionManager.getInstance().getCurrentConnectionEntity(), WifiListActivity.this);
                    wifiSetDialog.dismiss();
                }
            });
            wifiSetDialog.setNegativeButton(getString(R.string.forget), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    wifiSetDialog.dismiss();
                }
            });
        } else {
            wifiSetDialog.setPositiveButton(getString(R.string.sure), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String pwd = wifiSetDialog.getPasword();
                    if (TextUtils.isEmpty(pwd)) {
                        showToast(getString(R.string.password_can_not_empty));
                        return;
                    }
                    JSONObject jsonParams = new JSONObject();
                    try {
                        jsonParams.put("ssid", wifiBean.ssid);
                        jsonParams.put("password", pwd);
                        jsonParams.put("encrypt", "WPA2PSK-AES");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    loadingDialog();
                    try {
                        SharedUtil.getInstance().writeWifiInfo(jsonParams.getString("ssid"), jsonParams);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    //配置Wifi，并连接
                    NetworkManager.getInstance().WLANConfig(ConnectionManager.getInstance().getCurrentConnectionEntity(), jsonParams, WifiListActivity.this);
                    wifiSetDialog.dismiss();
                }
            });
            wifiSetDialog.setNegativeButton(getString(R.string.cancel), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    wifiSetDialog.dismiss();
                }
            });
        }
        wifiSetDialog.show();
    }

    /**
     * 配置Wifi连接的灰调函数
     *
     * @param ret
     * @param apJsonString
     */
    @Override
    public void onWlanConfigCallBack(int ret, String apJsonString) {
        if (ret == 0) {
            hideloadingDialog();
            finish();
        }
    }

    /**
     * 断开连接的回调函数
     *
     * @param ret
     * @param apJsonString
     */
    @Override
    public void onWlanDisconnectCallBack(int ret, String apJsonString) {
        hideloadingDialog();
        if (ret == 0) {
            finish();
        }
    }
}
